# This file is used to create a login blueprint for the flask application.
# The blueprint is used to handle the login functionality of the application.


from flask import Blueprint
from flask import request
from flask import jsonify
import psycopg2.extras
from settings import *
from database import PostgreSingleton
from database.wx_login_methods import WxLoginMethods
from database.wx_token_table_methods import WxTokenTableMethods
from database.wx_user_table_methods import WxUserTableMethods
from database.wx_access_token import WxAccessTokenTableMethods
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

web_login_blueprint = Blueprint('web_login_blueprint', __name__)


@web_login_blueprint.route('/web_login', methods=['POST'])
def web_login():

    # Get the request data from the client
    username = request.form.get('username')
    password = request.form.get('password')

    # Check if the phone number and password are valid
    if not username or not password:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "Invalid phone number or password",
            "resultBody": None

        }

        return jsonify(args_error)

    # 先写死一个用户 账号：18632682635 密码：BaiNa-0109
    # 后面再改成从数据库中查询 TODO

    if not (username == '18632682635' and password == 'BaiNa-0109'):
        args_error = {
            "status": -1,
            "errorCode": 1002,
            "errorMsg": "password or phone number error",
            "resultBody": None

        }

        return jsonify(args_error)
    
    with PostgreSingleton() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        wx_login_methods = WxLoginMethods(conn, cur)

        # Generate a token for the user
        wx_login_methods = WxTokenTableMethods(conn, cur)

        token_content = wx_login_methods.insert_token(5)

        return jsonify({
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": {
                "token": token_content
            }
        })
        